var socket;
var lockReconnect = false;
var reconectTime =0;
var heartCheck = {
    timeout: 40000,
    timeoutObj: null,
    serverTimeoutObj: null,
    reset: function(){
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
　　　　  return this;
    },
    start: function(){
        var self = this;
        this.timeoutObj = setTimeout(function(){
        	var obj = {'action': '13',
        				'body':me
        				}
        	socket.send(JSON.stringify(obj));
            self.serverTimeoutObj = setTimeout(function(){
            	socket.close();//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            }, self.timeout)
        }, this.timeout)
    },
}

function reconnect() {
    if (lockReconnect) return;
    lockReconnect = true;
    setTimeout(function () {     //没连接上会一直重连，设置延迟避免请求过多
    	if(reconectTime++>2){
    		layer.alert('网络连接失败,请重试', {
    			  skin: '#0383cc'/*'layui-layer-lan'*/ //样式类名
    			  ,closeBtn: 0
    			}, function(){
    			  window.location.href="/";
    			});
    		return;
    	}
        createWebSocket();
        lockReconnect = false;
    }, 2000);
}

function createWebSocket() {
        socket = new WebSocket("ws://" + url + ':' + port + '?id='+me+'&sessionId='+sessionId);
        initEventHandle();
}

function initEventHandle() {
	socket.onclose = function () {
		console.log("close");
        reconnect();
    };
    socket.onerror = function () {
    	console.log("error");
        reconnect();
    };
    socket.onopen = function () {
    	console.log(username+"登陆成功...");
        heartCheck.reset().start();      //心跳检测重置
        socket.send(JSON.stringify({'action': '8', 'body': '{me:'+me+',name:'+username+'}'}));
    };
    socket.onmessage = function (event) {    //如果获取到消息，心跳检测重置
        heartCheck.reset().start();      //拿到任何消息都说明当前连接是正常的
        handMsg(event);
    };
}

function initEventBind(){
	
	$("html").click(function(){
        $(".layui-layim-photos").each(function(){
        	$(this).parent().css("max-width","30%");
        });
    });
}
//聊天窗口切换
function tabChatChange(data){
	data = data || {};
	 var id = data.id;
	 var type = data.type;
	 if(id == null || type ==null){
		 return ;
	 }
	if(!$(".layim-chat-list").find("layim-"+type+id).hasClass("layim-this")){
		$(".layui-layim-list li").each(function(){
			//选择用户
			if($(this).hasClass("layim-"+type+id)){
				var status =$(this).find(".layim-msg-status");
				status.text(0);
				status.css("display","none");
			}
		});
	 }
}

function unreadMsg(data){
	
	 data = data || {};
	 var id = data.id;
	 var type = data.type;
	 if(id == null || type ==null){
		 return ;
	 }
		 //判断是否当前窗口
		 if(!$(".layim-chat-list").find("layim-"+type+id).hasClass("layim-this")){
			 if($(".layim-chat-list").parent().parent().css("display") == "none"){
				 
			 }else if($(".layim-chat-list").find("li").length ==1){
				 //只有当前一个窗口
				 return;
			 }
			$(".layui-layim-list li").each(function(){
				//选择用户
				if($(this).hasClass("layim-"+type+id)){
					//加未读标识
					var status =$(this).find(".layim-msg-status");
					var count = status.text();
					if(isNaN(count)){
						count =0;
					}
					status.text(++count);
					status.css("display","block");
				}
			});
		 }
}
//监听接受到消息事件
function handMsg(res) {
	layui.use(['layim'], function (layim) {
	    console.log("接收到消息...");
	    console.log(res);
	    var data = res.data;
	    data = JSON.parse(data);
	    console.log("data:");
	    console.log(data);
	    var body = JSON.parse(data.body);
	    if (data.action != 'undefined') {
	        switch (data.action) {
	            case parseInt(TYPE.P2PMSG):
	            	var body =JSON.parse(data.body);
	                layim.getMessage(body);
	            	unreadMsg(body);
	                break;
	            case parseInt(TYPE.GROUP_MSG_REQ):
	                layim.getMessage(JSON.parse(data.body));
	            	unreadMsg(body);
	                break;
	            case parseInt(TYPE.OLDMSG):
	                layim.getMessage(JSON.parse(data.body));
	            	unreadMsg(body);
	                break;
	            case parseInt(TYPE.SUCCESS_MESSAGE_RESP):
	                layer.msg(body.msg, {icon: 1, offset: 'lb'});
	                $('#loading').hide();
	                $('#onlineCount').show();
	                $('#onlineCount').text(body.count);
	                break;
	            case parseInt(TYPE.FAIL_MESSAGE_RESP):
	                layer.msg(body.msg, {icon: 5, offset: 'lb'});
	                $('#loading').hide();
	                $('#onlineCount').show();
	                $('#onlineCount').text(body.count);
	                break;
	            case parseInt(TYPE.REQFRIEND):
	                layim.msgbox("新");
	                break;
	            case parseInt(TYPE.REQFRIENDSUCCESS):
	                //console.log("对方同意加好友...");
	                layim.msgbox("新");
	                var userJson = {
	                    type: 'friend'
	                    , avatar: body.user.avatar //好友头像
	                    , username: body.user.username //好友昵称
	                    , groupid: body.group //所在的分组id
	                    , id: body.user.id //好友ID
	                    , sign: body.user.sign //好友签名
	                };
	                layim.addList(userJson);
	                contextMenuInitFriend();
	                break;
	            case parseInt(TYPE.JOIN_GROUP_REQ):
	                layim.addList(body);
	                socket.send(JSON.stringify(data));
	                contextMenuInitGroup(); 
	              //查询是否有未读消息
	                $.ajax({
	                    url: '/mychat/user/unreadMsgCount',
	                    success: function (data) {
	                        if (data.count > 0) {
	                            layim.msgbox(data.count); //数字即为你通过websocket或者Ajax实时获取到的最新消息数量
	                        }
	                    }
	                });
	                break;
	            case parseInt(TYPE.ONLINECOUNT):
	                $('#loading').hide();
	                $('#onlineCount').show();
	                $('#onlineCount').text(body.count);
	                break;
	            case parseInt(TYPE.QUIT_GROUP_RESP):
	            	quitGroup(body.id);
	                  //查询是否有未读消息
	                    $.ajax({
	                        url: '/mychat/user/unreadMsgCount',
	                        success: function (data) {
	                            if (data.count > 0) {
	                                layim.msgbox(data.count); //数字即为你通过websocket或者Ajax实时获取到的最新消息数量
	                            }
	                        }
	                    });
	                break;
	            case parseInt(TYPE.DELFRIEND):
	            	delFriend(body.me);
	                  //查询是否有未读消息
	                    $.ajax({
	                        url: '/mychat/user/unreadMsgCount',
	                        success: function (data) {
	                            if (data.count > 0) {
	                                layim.msgbox(data.count); //数字即为你通过websocket或者Ajax实时获取到的最新消息数量
	                            }
	                        }
	                    });
	                break;
	            default:
	               // layer.msg("非法消息规格!");
	                break;
	        }
	    }
	});
};

function reloadConfig(){
	layui.use(['layim'], function (layim) {
		layim.config({
	        init: {
	            url: base + '/user/getInitData',
	            type: 'get'
	        },
	        chatLog: layui.cache.dir + 'css/modules/layim/html/chatlog.html',
	        msgbox: layui.cache.dir + 'css/modules/layim/html/msgbox.html',
	        brief: false,
	        find: base + '/find.html', //发现页面地址，若不开启，剔除该项即可,
	        title: username,
	        copyright:true ,
	        //可同时配置多个
	       /*  tool: [{
		     alias: 'code' //工具别名
		     ,title: '代码' //工具名称
		     ,icon: '&#xe64e;' //工具图标，参考图标文档
		 	}] , */
	        uploadImage: {
	            url:'/mychat/upload/image',
	            name:""
	        },
	        //上传文件接口
	        uploadFile: {
	            url: '/mychat/upload/files' //接口地址
	            , type: 'post' //默认post
	            ,name:""
	        }
	        //查看群员接口
	        , members: {
	            url: base + '/user/getMembers'
	            , data: {}
	        },
	        notice: true,
	       // isAudio: true, //开启聊天工具栏音频
	        //isVideo: true, //开启聊天工具栏视频
	    });
	 });
}

//清除多余群聊
function clearOtherGroup(){
	layui.use(['layim'], function (layim) {
		 var cache  =layui.layim.cache();
		 var local = layui.data('layim')[cache.mine.id]; //获取当前用户本地数据
		 var flag = false;
		 for(var i in cache.history) {
			 //群
		     if(i.indexOf("group")!=-1){
		    	 var isMyGroup = false;
		    	 var id =0;
		    	 for(var j in cache.group){
		    		 id =cache.group[j].id;
		    		 if("group"+id == i){
		    			 isMyGroup = true;
		    			 break;
		    		 }
		    	 }
		    	 if(!isMyGroup){
		    		 delete local.history.i;
		    		 quitGroup(id);
		    		 flag = true;
		    	 }
		     }

		}
		 if(flag){
			 layui.data('layim', {
				 key: cache.mine.id
				 ,value: local
			 });
		 }
	});
}
function clearOtherFriend(){
	layui.use(['layim'], function (layim) {
		 var cache  =layui.layim.cache();
		 var local = layui.data('layim')[cache.mine.id]; //获取当前用户本地数据
		 var flag = false;
		 for(var i in cache.history) {
			 //好友
		     if(i.indexOf("friend")!=-1){
		    	 var isMyFriend = false;
		    	 var id = 0;
		    	 for(var j in cache.friend){
		    		 id =cache.friend[j].id;
		    		 if("friend"+ id== i){
		    			 isMyGroup = true;
		    			 break;
		    		 }
		    	 }
		    	 if(!isMyFriend){
		    		 delete local.history.i;
		    		 delFriend(id);
		    		 flag = true;
		    	 }
		     }

		}
		 if(flag){
			 layui.data('layim', {
				 key: cache.mine.id
				 ,value: local
			 });
		 }
	});
}
function contextMenuInitFriend(){
	$(".layim-list-friend >li>h5").contextMenu({
        width: 140, // width
        itemHeight: 30, // 菜单项height
        bgColor: "#fff", // 背景颜色
        color: "#333", // 字体颜色
        fontSize: 15, // 字体大小
        hoverBgColor: "#009bdd", // hover背景颜色
        hoverColor: "#fff", // hover背景颜色
        target: function(ele) { // 当前元素
        	targetObj = ele.parent();
        //	console.log(targetIndex);
        //	console.log(ele);
        },
        menu: [
        	{ // 菜单项
                text: "新建分组",
                icon: "&#xe654",
                callback: function(ele) {
                	layer.prompt({title: '新建分组', formType: 0, maxlength: 7,shade :0,btnAlign: 'c'}, function(value, index){
                		layer.close(index);
                		var index = layui.layer.msg('请稍候',{icon: 16,time:false,shade:0.8});
                		$.get("user/addGroup",{"groupname":value},function(res){
                			layer.close(index);
                   			if(res.ok==true){
                   				$('.layim-list-friend').append('<li><h5 layim-event="spread" lay-type="false" data-id="'+res.data.id+'"><i class="layui-icon">&#xe602;</i><span>'+res.data.name+'</span><em>(<cite class="layim-count"> 0</cite>)</em></h5><ul class="layui-layim-list"><li class="layim-null">该分组下暂无好友</li></ul></li>');
                   				layer.msg("新建成功");
                   				reloadConfig();
                   			}else{
                   				layer.msg("新建失败");
                   			}
                   			
                   		});
                	});
                }
            },
            { // 菜单项
                text: "修改分组",
                icon: "&#xe642",
                callback: function(ele) {
                	layer.prompt({title: '新建分组', formType: 0, maxlength: 7,shade :0,btnAlign: 'c'}, function(value, index){
                		layer.close(index);
                		var index = layui.layer.msg('请稍候',{icon: 16,time:false,shade:0.8});
	                	targetIndex = $('.layim-list-friend >li').index(targetObj);
	                	layer.prompt({title: '新分组名称', formType: 0, maxlength: 7,shade :0,value:$(targetObj).find("span:first").text(),btnAlign: 'c'}, function(value, index){
	                		$.get("user/updateGroup",{"groupname":value,"targetIndex":targetIndex},function(res){
	                			layer.close(index);
	                			if(res.code==1){
	                				targetObj.find("span:first").text(value);
	                				layer.msg("修改成功");
	                			}else{
	                				layer.msg("修改失败");
	                			}
	                			
	                		});
	                	});
                	});
                }
            },
            {
                text: "删除分组",
                icon: "&#x1006",
                callback: function(ele) {
                    	 var msg ="删除分组将删除分组下所有好友？";
                       	 layer.confirm(msg, {icon: 3, title: '提示信息'}, function (index) {
                       		 layer.close(index);
                     		 var index = layui.layer.msg('请稍候',{icon: 16,time:false,shade:0.8});
                       		 targetIndex = $('.layim-list-friend >li').index(targetObj);
                       		 id = targetObj.attr("data-id");
		                		$.get("user/deleteGroup",{"targetIndex":targetIndex,"id":id},function(res){
		                			layer.close(index);
		                			if(res.code==1){
		                				targetObj.remove();
		                				layer.msg("删除成功");
		                				if($('.layim-list-friend >li').length==0){
		                					window.location.reload();
		                				} 
		                				reloadConfig();
		                			}else{
		                				layer.msg(res.msg);
		                			}
		                	 });		
                       	 });	
                 }
            }
        ]
    });
		
        $(".layim-list-friend >li > ul >li").contextMenu({
            width: 140, // width
            itemHeight: 30, // 菜单项height
            bgColor: "#fff", // 背景颜色
            color: "#333", // 字体颜色
            fontSize: 15, // 字体大小
            hoverBgColor: "#009bdd", // hover背景颜色
            hoverColor: "#fff", // hover背景颜色
            target: function(ele) { // 当前元素
            	targetObj = ele;
            },
            menu: [
                /* {
                    text: "修改备注",
                    icon: "&#xe642",
                    callback: function(ele) {
                    	   var uid = $.trim(targetObj.attr("class").replace(/^layim-friend/g, ''));
                    	   layer.prompt({title: '好友备注', formType: 0, maxlength: 7,shade :0,value:$(targetObj).find("span:first").text(),btnAlign: 'c'}, function(value, index){
                        		$.get("updateRemark",{"uid":uid,"remark":value},function(res){
                        			if(res.code==0){
                        				targetObj.find("span:first").text(value);
                        				layer.msg("修改成功");
                        			}else{
                        				layer.msg("修改失败");
                        			}
                        			layer.close(index);
                        		});
                        	});
                    }
                }, */
               /*  {
                    text: "移动分组",
                    icon: "&#xe604",
                    callback: function(ele) {
                        
                    }
                }, */
                {
                    text: "删除好友",
                    icon: "&#x1006",
                    callback: function(ele) {
                    	var uid = $.trim(targetObj.attr("class").replace(/^layim-friend/g, ''));
                    	var msg ="确定删除好友？"
                    		
                    	 layer.confirm(msg, {icon: 3, title: '提示信息'}, function (index) {
                    		layer.close(index);
                    		var index = layui.layer.msg('请稍候',{icon: 16,time:false,shade:0.8});
	                    	$.get("user/deleteFriend",{"uid":uid},function(res){
	                    		 layer.close(index);
	                    		 if(res.code==1){
	                    			 delFriend(uid);
	                    			 layer.msg("删除成功");
	                    		 }else{
	                    			 layer.msg("删除失败");
	                    		 }
	                    	});
                    	 });
                    }
                }   
            ]
        });
		
}

function contextMenuInitGroup(){
		//群事件
	$(".layim-list-group > li").contextMenu({
        width: 140, // width
        itemHeight: 30, // 菜单项height
        bgColor: "#fff", // 背景颜色
        color: "#333", // 字体颜色
        fontSize: 15, // 字体大小
        hoverBgColor: "#009bdd", // hover背景颜色
        hoverColor: "#fff", // hover背景颜色
        target: function(ele) { // 当前元素
        	targetObj = ele;
        },
        menu: [
        	/* { // 菜单项
                text: "修改名片",
                icon: "&#xe642",
                callback: function(ele) {
                	var uid = $.trim(targetObj.attr("class").replace(/^layim-group/g, ''));
                	$.get("lookGroupRemark",{"uid":uid},function(res){
                		layer.prompt({title: '新的群名片', formType: 0, maxlength: 7,shade :0,value:res.data.bevymember.remark,btnAlign: 'c'}, function(value, index){
                    		$.get("modifyBevyRemark",{"uid":uid,"remark":value},function(data){
                    			if(res.code==0){
                    				layer.msg("修改成功");
                    			}else{
                    				layer.msg("修改失败");
                    			}
                    			layer.close(index);
                    		});
                    	});
                	});	                        	 
                }
            }, */
        	{ // 菜单项
                text: "创建群组",
                icon: "&#xe654",
                callback: function(ele) {
                	layui.layer.open({
              		  type: 2,
              		  title: '创建群组',
              		  closeBtn: 1, //不显示关闭按钮
              		  fixed: false,
              		  maxmin:true,
              		  shade:0,
              		  offset: 'auto',
              		  area: ['370px', '350px'],
              		  content: [layui.cache.dir + 'css/modules/layim/html/createGroup.html', 'no'], //iframe的url，no代表不显示滚动条
              		  end: function(){ 
              			reloadConfig();
              			contextMenuInitGroup();
              		  }
              		});            	 
                }
            }, 
        	{ // 菜单项
                text: "退出该群",
                icon: "&#x1006",
                callback: function(ele) {
                     var fid = $.trim(targetObj.attr("class").replace(/^layim-group/g, ''));
                     var res = layui.layim.cache();
                     var msg ="确定退出此群聊？";
                     var groups = res.group;
                     for(var i=0;i<groups.length;i++){
                    	 console.log(groups[i].id == fid);
                    	 if(groups[i].id == fid){
                    		 if(groups[i].userid == res.mine.id){
                    			 msg ="系统检测到您是群主，退出将解散该群";
                    		 }
                    		 break;
                    	 }
                     }
                	 layer.confirm(msg, {icon: 3, title: '提示信息'}, function (index) {
                		 
                    	$.get("user/exitGroup",{"fid":fid},function(res){
                    		layer.close(index);
                    		 if(res.code==1){
                    			 
                    			 var obj ={
                    					 "action":4,
                    					 "body" :"{\"id\" :"+fid+"}"
                    			 };
                    			 socket.send(JSON.stringify(obj));
                    			 quitGroup(fid); 
                    			 layer.msg("退出成功");
                    		 }else{
                    			 layer.msg(res.msg);
                    		 }
                    	});
                	 });
                }
            }
        ]
    });
}

//退群
function quitGroup(fid){
	layui.use(['layim'], function (layim) {
		layim.removeList({
			  type: 'group' 
			  ,id: fid 
			});
		
		if($(".layim-list-history").find("layim-group"+fid)!=null){
			$(".layim-list-history .layim-group"+fid).remove();
		 }
		if($(".layim-chat-list").find("layim-group"+fid)!=null){
			$(".layim-chat-list .layim-group"+fid).find("i").click();
		}
		 $(".layui-layer").each(function(index){
			 if($(this).find("layim-group"+fid)!=null){
				 if(index>0 && $(this).find(".layui-layer-title").text()!="查找"){
					 if($(this).find(".layim-chat-list")){
					 		$(this).find("layim-group"+fid).find("i").click();
					 	}else{
					 		$(this).remove();
					 	}
				 }
			 }
		 });
		
		 var cache  =layui.layim.cache();
		 var local = layui.data('layim')[cache.mine.id]; //获取当前用户本地数据
		 
		 delete local.history["group"+fid];
		 layui.data('layim', {
			  key: cache.mine.id
			  ,value: local
			});
		 $(".layui-layer-shade").remove();
	 });
}

//删除好友
function delFriend(id){
	layui.use(['layim'], function (layim) {
		layim.removeList({
			  type: 'friend' 
			  ,id: id 
			});
		
		if($(".layim-list-history").find("layim-friend"+id)!=null){
			$(".layim-list-history .layim-friend"+id).remove();
		 }
		if($(".layim-chat-list").find("layim-friend"+id)!=null){
			$(".layim-chat-list .layim-friend"+id).find("i").click();
		}
		 
		 $(".layui-layer").each(function(index){
			 if($(this).find("layim-friend"+id)!=null){
				 if(index>0 && $(this).find(".layui-layer-title").text()!="查找"){
					 	if($(this).find(".layim-chat-list")){
					 		$(this).find("layim-friend"+id).find("i").click();
					 	}else{
					 		$(this).remove();
					 	}
					 	
				 }
			 }
		 });
		
		 var cache  =layui.layim.cache();
		 var local = layui.data('layim')[cache.mine.id]; //获取当前用户本地数据
		 
		 delete local.history["friend"+id];
		 layui.data('layim', {
			  key: cache.mine.id
			  ,value: local
			});
		 $(".layui-layer-shade").remove();
	 });
}